package org.example.FTP;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class FileClient {
    private static final String SERVER_IP = "localhost";
    private static final int SERVER_PORT = 8888;
    private static final String DOWNLOAD_DIR = "D:\\logs\\client\\test1"; // 客户端下载文件保存目录

    public static void main(String[] args) {
        // 创建下载目录
        new File(DOWNLOAD_DIR).mkdirs();

        try (
            Socket socket = new Socket(SERVER_IP, SERVER_PORT);
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            Scanner scanner = new Scanner(System.in)
        ) {
            System.out.println("已连接到文件服务器");
            System.out.println("请选择操作：1-上传文件 2-下载文件");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            if (choice == 1) {
                uploadFile(scanner, dos, dis);
            } else if (choice == 2) {
                downloadFile(scanner, dos, dis);
            } else {
                System.out.println("无效的选择");
            }

        } catch (IOException e) {
            System.err.println("客户端错误：" + e.getMessage());
        }
    }

    // 上传文件到服务器
    private static void uploadFile(Scanner scanner, DataOutputStream dos, DataInputStream dis) throws IOException {
        // 发送操作类型
        dos.writeUTF("UPLOAD");

        // 输入要上传的文件路径
        System.out.println("请输入要上传的文件路径：");
        String filePath = scanner.nextLine();
        File file = new File(filePath);

        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在或不是有效文件");
            return;
        }

        // 发送文件名和大小
        String fileName = file.getName();
        dos.writeUTF(fileName);
        dos.writeLong(file.length());
        System.out.println("准备上传文件：" + fileName + "，大小：" + file.length() + "字节");

        // 发送文件内容
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalSent = 0;

            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
                totalSent += bytesRead;
                // 显示上传进度
                System.out.printf("上传进度：%.2f%%\r", (totalSent * 100.0) / file.length());
            }
        }

        // 接收服务器响应
        String response = dis.readUTF();
        System.out.println("\n服务器响应：" + response);
    }

    // 从服务器下载文件
    private static void downloadFile(Scanner scanner, DataOutputStream dos, DataInputStream dis) throws IOException {
        // 发送操作类型
        dos.writeUTF("DOWNLOAD");

        // 输入要下载的文件名
        System.out.println("请输入要下载的文件名：");
        String fileName = scanner.nextLine();
        dos.writeUTF(fileName);

        // 接收服务器响应
        String status = dis.readUTF();
        if ("ERROR".equals(status)) {
            System.out.println("服务器上不存在该文件");
            return;
        }

        // 读取文件名和大小
        String receivedFileName = dis.readUTF();
        long fileSize = dis.readLong();
        System.out.println("准备下载文件：" + receivedFileName + "，大小：" + fileSize + "字节");

        // 保存下载的文件
        File file = new File(DOWNLOAD_DIR + receivedFileName);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalRead = 0;

            while (totalRead < fileSize && (bytesRead = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalRead += bytesRead;
                // 显示下载进度
                System.out.printf("下载进度：%.2f%%\r", (totalRead * 100.0) / fileSize);
            }
        }

        System.out.println("\n文件下载完成，保存路径：" + file.getAbsolutePath());
    }
}
